<?php

	class Nmysql extends mysqli {
		private $host;
		private $user;
		private $passwd;
		private $dbname;

		private $latest_query = array();

		public function __construct(){
			$mysqli = new mysqli();

			$this->host		= MYSQL_HOST;
			$this->user		= MYSQL_USER;
			$this->passwd	= MYSQL_PASS;
			$this->dbname	= MYSQL_NAME;
			parent::__construct($this->host, $this->user, $this->passwd, $this->dbname);

			# 연결되지 않았을 경우
			if(mysqli_connect_error()){
				die('Connect Error ('.mysqli_connect_errno().') '.mysqli_connect_error());
			}

			# 문자셋
			//$chrset = parent::character_set_name();
			//if(strcmp($chrset,'utf8')) parent::set_charset(str_replace('-','',_CHRSET_));
			parent::query("set names utf8");

		}




		####################################################
		# public method                                    #
		####################################################

//		public function execute($query = NULL){
//			$this->flush();
//			$query = trim($query);
//			$this->last_query = $query;
//			$this->affected_row = $this->db->exec($query);
//			if ( $this->catch_error() ) return false;
//			return $this->affected_row;
//		}

		# 데이터 베이스의 데이터를 배열로 리턴 (result array)
		# res >> results
		# cnt >> count
		# has >> 데이터 존재 여부
		#
		#	example)
		#		$article = $db->gets(sprintf("SELECT * FROM `fruits`"), 'puts');
		#		$article = $db->gets(sprintf("SELECT fuid, name, name_eng, enable FROM `fruits`"), 'puts');
		#	출력 >> Array
		#		(
		#			[res] => Array
		#				(
		#					[0] => Array
		#						(
		#							[fuid] => 1
		#							[name] => 오렌지
		#							[name_eng] => orange
		#							[enable] => Y
		#						)
		#
		#						)
		#
		#					...
		#
		#					[10] => Array
		#						(
		#							[fuid] => 11
		#							[name] => 구아바
		#							[name_eng] => Guava
		#							[enable] => Y
		#						)
		#
		#				)
		#
		#			[cnt] => 11
		#			[has] => 1
		#		)
		public function gets($query=NULL, $data_print='') {
			$this->latest_query[] = $query;
			preg_match("/[*]/i", $query, $matches);
			$result_arr = array();
			if(@$matches[0] == '*'){
				# 리스팅
				$res = parent::query($query);
				while ($row = $res->fetch_array(MYSQLI_ASSOC)){
					//Nlog::puts(count($row));
					$result_arr['res'][] = $row;
				}

				# 카운팅
				$query = preg_replace("/[*]/i", "count(*)", $query);
				//Nlog::puts("original query",$query);

				# LIMITED SELECT COUNT(*)
				$ismatch = preg_match("/LIMIT (.*?), (.*?);/",$query);
				if($ismatch) {
					$query = preg_replace("/FROM /", "FROM (SELECT 1 FROM ", $query);
					$query = preg_replace("/ORDER BY `(.*?)` (DESC|ASC)/", "", $query);
					$ismatche = preg_match("/LIMIT (.*?), (.*?);/", $query);
					$query = preg_replace("/;/","",$query);
					if($ismatche){
						$query .= ") cnt;";
					}
					//Nlog::puts("match!, converted query",$query);
					# SELECT COUNT(*) FROM (SELECT 1 FROM `ggo_cfg_packages_pref` LIMIT 10, 10) cnt;
				}
				$cnt = parent::query($query)->fetch_row();

				//Nlog::puts('cnt', $cnt);
				$result_arr['cnt'] = $cnt[0];

				# 데이터가 존재 여부.
				if($result_arr['cnt'] > 0){
					$result_arr['has'] = TRUE;
				} else {
					$result_arr['res'] = array();
					$result_arr['has'] = FALSE;
				}

				/*/
				# 데이터 존재 여부
				if( count($result_arr['cnt']) > 0 ){
					$result_arr['has'] = TRUE;
				} else {
					$result_arr['res'] = array();
					$result_arr['has'] = FALSE;
				}
				//*/

				$ret = $result_arr;
			} else {
				# 리스팅
				$res = parent::query($query);
				while ($row = $res->fetch_array(MYSQLI_ASSOC)){
					$result_arr['res'][] = $row;
				}

				# 카운팅
				$cnt = parent::num_rows;
				$result_arr['cnt'] = $cnt;

				# 데이터가 존재 여부.
				if($cnt > 0){
					$result_arr['has'] = TRUE;
				} else {
					$result_arr['has'] = FALSE;
				}

				# 데이터 존재 여부
				if(count($result_arr['cnt']) > 0){
					$result_arr['has'] = TRUE;
				} else {
					$result_arr['has'] = FALSE;
				}

				$ret =  $result_arr;
			}

			# 데이터를 찍어 볼 것인가.
			if($data_print != ''){
				if($data_print == 'puts') {
					Nlog::puts($ret);
				} elseif($data_print == 'puts') {
					Nlog::puts($ret);
				} else {
					echo "<puts>"; print_r($ret); echo "</puts>";
				}
			}
			return $ret;
		}


		# 데이터 베이스의 데이터를 배열로 리턴 (row array)
		# res >> row
		# cnt >> count
		# has >> 데이터 존재 여부
		#
		#	example)
		#		$article = $db->get(sprintf("SELECT * FROM `fruits` WHERE `fuid`= '3'"), 'puts');
		#		$article = $db->get(sprintf("SELECT fuid, name, name_eng, enable FROM `fruits` WHERE `fuid`= '1'"), 'puts');
		#	출력 >> Array
		#		(
		#			[res] => Array
		#				(
		#					[fuid] => 1
		#					[name] => 오렌지
		#					[name_eng] => orange
		#					[enable] => Y
		#				)
		#
		#			[cnt] => 1
		#			[has] => 1
		#		)
		public function get($query=NULL, $data_print='') {
			$this->latest_query[] = $query;
			$result_arr = array();
			if(preg_match("/[*]/i", $query)){
				# 리스팅
				$res = parent::query($query)->fetch_array(MYSQLI_ASSOC);
				$result_arr['res'] = $res;

				# 카운팅
				$query = preg_replace("/[*]/i", "count(*)", $query);
				$cnt =  parent::query($query)->fetch_row();
				$result_arr['cnt'] = $cnt[0];

				# 데이터 존재 여부.
				if($result_arr['cnt'] > 0){
					$result_arr['has'] = TRUE;
				} else {
					$result_arr['has'] = FALSE;
				}

				$ret = $result_arr;
			} else {
				# 리스팅
				$res = parent::query($query);
				while ($row = $res->fetch_array(MYSQLI_ASSOC)){
					$result_arr['res'] = $row;
				}

				# 카운팅, 데이터 존재 여부.
				if(is_array($result_arr['res']) == TRUE){
					$result_arr['cnt'] = 1;
					$result_arr['has'] = TRUE;
				} else {
					$result_arr['cnt'] = 0;
					$result_arr['has'] = FALSE;
				}

				$ret =  $result_arr;
			}

			# 데이터를 찍어 볼 것인가.
			if($data_print != ''){
				if($data_print == 'puts') {
					Nlog::puts($ret);
				} elseif($data_print == 'puts') {
					Nlog::puts($ret);
				} else {
					echo "<puts>"; print_r($ret); echo "</puts>";
				}
			}
			return $ret;
		}


		# 데이터 베이스의 데이터를 배열로 리턴 (one data)
		# *** >> one data
		# cnt >> count
		# has >> 데이터 존재 여부
		#
		#	example)
		#		$article = $db->getone(sprintf("SELECT `name` FROM `fruits` WHERE `fuid`= 1"), 'puts');
		#	출력 >>
		#	Array
		#	(
		#		[name] => 오렌지
		#		[cnt] => 1
		#		[has] => 1
		#	)
		public function getone($query=NULL, $data_print='') {
			$this->latest_query[] = $query;
			$res = parent::query($query)->fetch_array(MYSQLI_ASSOC);
			$result_arr['res'] = $res;
			$result_arr = $res;

			# 카운팅, 데이터 존재 여부.
			if(is_array($result_arr) == TRUE){
				$result_arr['cnt'] = 1;
				$result_arr['has'] = TRUE;
			} else {
				$result_arr['cnt'] = 0;
				$result_arr['has'] = FALSE;
			}
			$ret = $result_arr;

			# 데이터를 찍어 볼 것인가.
			if($data_print != ''){
				if($data_print == 'puts') {
					Nlog::puts($ret);
				} elseif($data_print == 'puts') {
					Nlog::puts($ret);
				} else {
					echo "<puts>"; print_r($ret); echo "</puts>";
				}
			}
			return $ret;
		}

		# 전체 카운트를 얻는다
		public function getcnts($table_name, $data_print='') {
			$ret = parent::query(sprintf("SELECT count(*) as cnts FROM %s", $table_name))->fetch_array(MYSQLI_ASSOC);
			if($data_print != ''){
				if($data_print == 'puts') {
					Nlog::puts($ret);
				} elseif($data_print == 'puts') {
					Nlog::puts($ret);
				} else {
					echo "<puts>"; print_r($ret); echo "</puts>";
				}
			}
			return $ret['cnts'];
		}

		# 마지막 쿼리를 출력
		#	example)
		#		Nlog::puts($db->get_latest_query());
		#	출력 >>
		#		Array
		#		(
		#			[0] => SELECT package_filename, package_desc FROM `ggo_cfg_packages` WHERE package_file = 'admin.package.process.php';
		#			[1] => UPDATE `ggo_cfg_packages` SET `package_filename` = '부트캠프12', `package_desc` = '꼬꼬 프레임워크의 시작점 입니다.' WHERE `puid` = 3;
		#			[2] => UPDATE `ggo_cfg_packages` SET `package_filename` = '로그인12', `package_desc` = '로그인' WHERE `puid` = 2;
		#			[3] => UPDATE `ggo_cfg_packages` SET `package_filename` = '로그인 처리12', `package_desc` = '로그인 처리' WHERE `puid` = 1;
		#		)
		public function get_latest_query($data_print='') {
			$ret = $this->latest_query;
			if($data_print != ''){
				$ret = "latest query >> " . $ret;
				if($data_print == 'puts') {
					Nlog::puts($ret);
				} elseif($data_print == 'puts') {
					Nlog::puts($ret);
				} else {
					echo "<puts>"; print_r($ret); echo "</puts>";
				}
			} else {
				return $ret;
			}
		}


		# 새로운 열을 삽입/수정/삭제, 영향받은 결과를 배열로 리턴.
		# affected >> 결과
		# has >> affected가 1보다 클시 TRUE
		public function que($query=NULL, $data_print='') {
			$this->latest_query[] = $query;
			$res = parent::query($query);
			$result_arr['affected'] = $this->affected_rows;
			if($result_arr['affected'] > 0){
				$result_arr['has'] = TRUE;
			} else {
				$result_arr['has'] = FALSE;
			}
			$ret = $result_arr;
			//echo self::affected_rows;

			# 데이터를 찍어 볼 것인가.
			if($data_print != ''){
				if($data_print == 'puts') {
					Nlog::puts($ret);
				} elseif($data_print == 'puts') {
					Nlog::puts($ret);
				} else {
					echo "<puts>"; print_r($ret); echo "</puts>";
				}
			}
			return $ret;
		}


		# 일반적인 mysqli::query를 사용하나 마지막 쿼리를 찍어볼 수 있다는 장점이 있다.
		public function q($query=NULL, $get_result = TRUE) {
			$this->latest_query[] = $query;
			$res = parent::query($query);
			if($get_result) {
				while ($row = $res->fetch_array(MYSQLI_ASSOC)){
					$result_arr[] = $row;
				}
				$ret = $result_arr;
				return $ret;
			}
		}

		#fetch.
		public function fa($res){
			if(is_resource($res)){
				$ret = $res->fetch_array(MYSQLI_ASSOC);
				return $ret;
			}
		}

		####################################################
		# meta database info                               #
		####################################################

		public function field_names($table_name, $data_print=FALSE) {

			$result_arr = array();
			$result = parent::query( "DESC $table_name" );
			while ($row = $result->fetch_array()) {
				$result_arr[] = $row[0];
			}

			if($data_print == TRUE){
				echo "<puts>";
				print_r($result_arr);
				echo "</puts>";
			}

			return $result_arr;
		}

		public function get_comment($table_name, $data_print=FALSE) {
			$result_arr = array();
			$result = parent::query( "SELECT `COLUMN_COMMENT` FROM information_schema.COLUMNS WHERE `TABLE_NAME` = '{$table_name}'" );
			while ($row = $result->fetch_array()) {
				$result_arr[] = $row['COLUMN_COMMENT'];
			}

			if($data_print == TRUE){
				echo "<puts>";
				print_r($result_arr);
				echo "</puts>";
			}

			return $result_arr;
		}

		# 테이블 생성여부 체크
		public function tablecheck($table,$db) {
			$result = mysql_list_tables($db);
			for($i = 0;$i < mysql_num_rows($result);$i++) {
				if($table == mysql_tablename($result,$i)) return true;
			}
			return false;
		}
		public function get_table_comment($table_name, $data_print=FALSE) {
			$result = $this->gets("SHOW TABLE STATUS LIKE '{$table_name}'");
			return $result[0]['Comment'];
		}

		public function __destruct(){
			//parent::close();
		}
	}